package com.pwt.controller.permission;

import com.pwt.common.DataNotFoundException;
import com.pwt.service.AttachmentService;
import com.pwt.utils.FileUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@Tag(name = "附件上传接口")
public class AttachmentController {
    @Autowired
    AttachmentService attachmentService;

    @Autowired
    HttpServletRequest request;

    @Autowired
    HttpServletResponse response;

    @PostMapping(value = "attachment/upload")
    @Operation(summary = "上传文件",description = "上传文件(swagger不好使,请使用postman调试!!!!!!!!!!!!!!!!!!!!!!!!)(swagger does not work , please use postman)")
    public String upload(@RequestPart(name = "file") MultipartFile file) throws IOException {
        StringBuffer requestURL = request.getRequestURL();
        String requestURI = request.getRequestURI();
        String servletPath = request.getServletPath();
        String host = requestURL.toString().replaceAll(servletPath,"");
        System.out.println(requestURL);
        System.out.println(requestURI);
        System.out.println(servletPath);
        System.out.println(host);
        return attachmentService.upload(file,request);
    }

    @GetMapping("attachment/{id}")
    @Operation(summary = "下载文件",description = "下载文件(直接使用浏览器效果更好)")
    public void file(@PathVariable(name = "id") String id) throws DataNotFoundException {
        attachmentService.download(id,response);
    }
}
